<template>
    <div style='height: auto; margin-top: 10px;'>
        <div>
            <!--头部筛选条件-->
            <div style='display: flex;justify-content: space-between; padding-bottom: 15px;'>
                <div>
                    <el-input placeholder='请输入客户名称进行搜索' prefix-icon='el-icon-search'
                              clearable
                              @clear='initList'
                              style='width: 250px;margin-right: 10px' v-model='queryForm.customerName'
                              @keydown.enter.native='initList'>
                    </el-input>
                    <el-button icon='el-icon-search' type='primary' @click='initList'>
                        搜索
                    </el-button>
                </div>

                <div>
                    <el-button icon='el-icon-refresh' style='display: inline-flex;margin-right: 8px' type='primary'
                               @click='flushTable'></el-button>
                    <el-upload v-show='false'
                               :show-file-list='false'
                               :before-upload='beforeUpload'
                               style='display: inline-flex;margin-right: 8px'
                               action='/employee/basic/import'>
                        <!--            :on-success="xxx"-->
                        <!--            :on-error="xxx"-->
                        <el-button type='success' icon='el-icon-upload2' @click='beforeUpload'>
                            导入数据
                        </el-button>
                    </el-upload>

                    <el-button type='success' @click='exportData' icon='el-icon-download' v-show='false'>
                        导出数据
                    </el-button>

                    <el-button type='primary' icon='el-icon-plus' @click='add'>
                        新增
                    </el-button>
                </div>
            </div>
            <!--头部筛选条件-->

            <!--主体表格-->
            <div>
                <el-table :row-style="{height:'40px'}" :data='list' border stripe size='mini' height='650'
                          :header-cell-style="{background:'#f5f7fa',color:'#606266'}" style="font-size: 14px">
                    <el-table-column type='index' label='序号' align='center' width='50'></el-table-column>
                    <!-- <el-table-column type="selection" align="left" width="55"></el-table-column> -->
                    <el-table-column prop='id' label='主键ID' align='left' v-if='idShow'></el-table-column>

                    <el-table-column prop='customerName' label='客户名称' align='left' :show-overflow-tooltip='true'>
                        <el-tag slot-scope='scope' @click='handleCopy(scope.row.customerName)'>{{ scope.row.customerName }}</el-tag>
                    </el-table-column>

                    <el-table-column prop='customerType' label='客户类型' width='80' align='left' :show-overflow-tooltip='true'></el-table-column>

                    <el-table-column prop='issueTime' label='证书生效时间' align='center' :show-overflow-tooltip='true'></el-table-column>

                    <el-table-column prop='expiryTime' label='证书到期时间' align='center' :show-overflow-tooltip='true'></el-table-column>

                    <el-table-column prop='delFlag' label='状态' width='100' align='center' :show-overflow-tooltip='true'>
                        <template slot-scope='scope'>
                            <el-tag v-if='scope.row.delFlag === 1' type='warning'>已删除</el-tag>
                            <el-tag v-if='scope.row.delFlag === 0' type='success'>正常</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop='createTime' label='创建时间' align='center' :show-overflow-tooltip='true'></el-table-column>

                    <el-table-column prop='updateTime' label='更新时间' align='center' :show-overflow-tooltip='true'></el-table-column>

                    <el-table-column label='操作' align='center' width='220'>
                        <template slot-scope='scope'>
                            <el-button @click='genLicense(scope.row)' style="padding:5px;margin: 2px;" :disabled='scope.row.delFlag === 1' type='success' icon="el-icon-download">生成证书</el-button>
                            <el-button @click='edit(scope.row)' style="padding:5px;margin: 2px;" type='primary' icon="el-icon-edit">编辑</el-button>
                            <el-button @click='del(scope.row)' style="padding:5px;margin: 2px;" type='danger' icon="el-icon-delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!--主体表格-->

            <!--分页导航-->
            <div style='display: flex;justify-content: flex-end'>
                <el-pagination
                    background
                    :current-page.sync='pageNum'
                    @size-change='pageSizeChange'
                    @current-change='pageNumChange'
                    layout='sizes, prev, pager, next, jumper, ->, total, slot'
                    :total='total'>
                </el-pagination>
            </div>
            <!--分页导航-->
        </div>

        <!-- 新增/编辑/查看 保存对话框 -->
        <el-dialog v-dialogDrag
                   custom-class="dialogClass"
                   :modal-append-to-body='false'
                   :title='operateTitle'
                   :visible.sync='saveDialogVisible'
                   :close-on-click-modal="false"
                   @close='saveFormReset(true)'
                   :width="'500px'"
                   top='20vh'>
            <el-form :model='saveForm' :rules='saveFormRules' ref='saveFormRef' label-width='150px' label-position='left'>
                <el-form-item label='主键ID' prop='id' v-show='false'>
                    <el-input v-model='saveForm.id'></el-input>
                </el-form-item>
                <el-form-item label='客户名称' prop='customerName'>
                    <el-input v-model='saveForm.customerName' maxlength='32' class='saveFormColumnWidth' placeholder='请输入客户名称' clearable></el-input>
                </el-form-item>
                <el-form-item label='证书发行时间' prop='issueTime'>
                    <el-date-picker class='saveFormColumnWidth'
                                    v-model='saveForm.issueTime'
                                    @change='onSelectIssueTime($event)'
                                    format='yyyy-MM-dd HH:mm:ss'
                                    value-format='yyyy-MM-dd HH:mm:ss'
                                    type='datetime'
                                    placeholder='选择证书发行时间'>
                    </el-date-picker>
                </el-form-item>
                <el-form-item label='证书到期时间' prop='expiryTime'>
                    <el-date-picker class='saveFormColumnWidth'
                                    v-model='saveForm.expiryTime'
                                    @change='onSelectExpiryTime($event)'
                                    format='yyyy-MM-dd HH:mm:ss'
                                    value-format='yyyy-MM-dd HH:mm:ss'
                                    :picker-options='pickerOptions'
                                    type='datetime'
                                    placeholder='选择证书到期时间'>
                    </el-date-picker>
                </el-form-item>

                <el-form-item label='客户类型' prop='customerType'>
                    <el-input v-model='saveForm.customerType' maxlength='32' class='saveFormColumnWidth' placeholder='客户类型：user、company、institution' clearable></el-input>
                </el-form-item>

                <el-divider v-if='this.saveForm.jsonFormat'></el-divider>

                <el-form-item label="是否json格式" prop='jsonFormat'>
                    <el-radio v-model="saveForm.jsonFormat" :label="true">是</el-radio>
                    <el-radio v-model="saveForm.jsonFormat" :label="false">否</el-radio>
                </el-form-item>

                <el-form-item label='证书校验参数' prop='licenseCheckModel' v-if='this.saveForm.jsonFormat'>
                    <el-input type='textarea' v-model='saveForm.licenseCheckModel' rows='5' class='saveFormColumnWidth' placeholder='请输入证书校验参数'></el-input>
                </el-form-item>

                <div v-if='!this.saveForm.jsonFormat'>
                    <el-form-item label="Mac地址" prop='macAddress'>
                        <el-input v-model='saveForm.macAddress' class='saveFormColumnWidth' placeholder='请输入mac地址，若有多个，使用逗号连接' clearable></el-input>
                    </el-form-item>
                    <el-form-item label="CPU序列号" prop='cpuSerial'>
                        <el-input v-model='saveForm.cpuSerial' class='saveFormColumnWidth' placeholder='请输入CPU序列号' clearable></el-input>
                    </el-form-item>
                    <el-form-item label="主板序列号" prop='mainBoardSerial'>
                        <el-input v-model='saveForm.mainBoardSerial' class='saveFormColumnWidth' placeholder='请输入主板序列号' clearable></el-input>
                    </el-form-item>
                </div>

                <el-form-item label='状态' prop='delFlag' v-if='this.saveForm.id'>
                    <el-select v-model="saveForm.delFlag" placeholder="请选择" class='saveFormColumnWidth'>
                        <el-option v-for="item in delFlags" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <span slot='footer' class='dialog-footer'>
                <el-button type='primary' @click='saveFormReset(false)' v-if='resetVisible'>重置</el-button>
                <el-button type='normal' @click='saveFormCancel()'>取消</el-button>
                <el-button type='primary' @click='saveFormConfirm()'>确定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { Message } from 'element-ui';
import { deepClone, isJson, strToDate } from '../utils/tool';
import {
    findPage,
    deleteById,
    checkCustomerName,
    insert,
    update,
    downloadLicense
} from '../api/CustomerLicenseInfoManageApi';
export default {
    name: 'CustomerLicenseInfoManage',
    data(){
        return {
            // table数据
            list: [],
            total: 0,
            pageNum: 1,
            pageSize: 10,

            // 控制 table 中id列显隐
            idShow: false,
            // 控制 保存对话框显隐
            saveDialogVisible: false,

            // 保存对话框的标题
            operateTitle: '',
            // 控制保存对话框中重置按钮显隐
            resetVisible: true,

            // table数据查询对象
            queryForm: {
                customerName: '',
            },
            // 转换常量
            delFlags: [
                {'label': '正常', 'value': 0},
                {'label': '已删除', 'value': 1},
            ],
            // 保存表单数据对象
            saveForm: {
                id: '',
                customerName: '',
                customerType: '',
                issueTime: '',
                expiryTime: '',
                delFlag: 0,
                jsonFormat: false,
                licenseCheckModel: '',
                macAddress: '',
                cpuSerial: '',
                mainBoardSerial: '',
            },
            // 保存表单字段校验规则
            saveFormRules: {
                customerName: [
                    { required: true, trigger: 'blur', validator: this.validCustomerName }
                ],
                issueTime: [
                    { required: true, trigger: 'blur', validator: this.validIssueTime }
                ],
                expiryTime: [
                    { required: true, trigger: 'blur', validator: this.validExpiryTime }
                ],
                licenseCheckModel: [
                    { required: true, trigger: 'blur', validator: this.validLicenseCheckModel }
                ],
                macAddress: [
                    { required: true, trigger: 'blur', validator: this.validMacAddress }
                ],
            },
            // 日期控件设置项
            pickerOptions: {
                // 限制证书到期时间必须大于当前时间 + 1天，必须大于证书发行时间
                'disabledDate'(time) {
                    return time.getTime() < (Date.now() - 25 * 3600 * 1000);
                }
            },
        }
    },
    mounted() {
        // 加载表数据
        this.initList();
    },
    methods: {
        // 初始化表格数据
        initList() {
            let params = {};
            params.customerName = this.queryForm.customerName;
            params.pageNum = this.pageNum;
            params.pageSize = this.pageSize;
            findPage(params).then(resp => {
                if (resp && resp.status === 200) {
                    this.list = resp.data.rows;
                    this.total = resp.data.total;
                }
            });
        },

        // 刷新表格
        flushTable() {
            this.initList();
            Message.success('刷新成功');
        },
        // 表格的pageNum变化，则修改调用接口的对应参数
        pageNumChange(page) {
            this.pageNum = page;
            this.initList();
        },
        // 表格pageSize变化，则修改调用接口的对应参数
        pageSizeChange(size) {
            this.pageSize = size;
            this.pageNum = 1;
            this.initList();
        },

        // 文件上传之前初始化选文件框
        beforeUpload() {
            Message.info('初始化选择文件框');
        },
        // 导出表数据
        exportData() {
            Message.info('导出数据');
        },

        // (新增数据)显示新增对话框
        add() {
            this.saveForm = {};
            this.operateTitle = '新增数据';
            this.resetVisible = true;
            this.saveDialogVisible = true;
        },
        // 删除数据
        del(row) {
            this.$confirm('删除后无法恢复！！！确认删除?')
                .then(() => {
                    deleteById(row).then(resp => {
                        if (resp && resp.status === 200) {
                            this.initList();
                            Message.success('删除成功');
                        }
                    });
                }).catch(ex => {
                console.error('删除异常：' + ex);
            });
        },
        // (编辑数据)显示编辑对话框
        edit(row) {
            // 防止编辑数据影响原数据，使用深拷贝数据来进行编辑
            this.saveForm = deepClone(row);
            this.operateTitle = '更新数据';
            this.resetVisible = false;
            this.saveDialogVisible = true;
        },
        // 保存表单-重置
        saveFormReset(silent) {
            if(this.$refs["saveFormRef" ] !== undefined) {
                this.$refs["saveFormRef" ].resetFields();
            }
            this.saveForm.customerName = '';
            this.saveForm.issueTime = '';
            this.saveForm.expiryTime = '';
            this.saveForm.licenseCheckModel = '';
            if (!silent) {
                Message.success('重置成功！');
            }
        },
        // 保存表单-取消
        saveFormCancel() {
            this.initList();
            this.saveDialogVisible = false;
        },
        // 选择证书发行时间
        onSelectIssueTime(value) {
            if (value) {
                this.saveForm.issueTime = value;
            }
        },
        // 选择证书过期时间
        onSelectExpiryTime(value) {
            if (value) {
                let date = strToDate(value);
                if (date.getTime() < new Date().getTime()) {
                }
                this.saveForm.expiryTime = value;
            }
        },

        // 校验客户名称
        validCustomerName(rule, value, callback) {
            if (!value) {
                callback(new Error('请输入客户名称！'));
            }
            // 调用后端接口查重
            checkCustomerName({'id': this.saveForm.id, 'customerName':value}).then(resp => {
                debugger;
                if (resp && resp.status === 200) {
                    if (resp.data) {
                        callback(new Error('客户名称已存在！'));
                    } else {
                        callback();
                    }
                }
            });
        },
        // 校验证书发行时间
        validIssueTime(rule, value, callback) {
            if (!value) {
                callback(new Error('请选择证书发行时间！'));
            }
            let issueTime = new Date(value);
            let expiryTime = new Date(this.saveForm.expiryTime);
            if (issueTime.getTime() >= expiryTime.getTime()) {
                callback(new Error("证书发行时间必须小于到期时间！"));
            }
            callback();
        },
        // 校验证书到期时间
        validExpiryTime(rule, value, callback) {
            if (!value) {
                callback(new Error('请选择证书到期时间！'));
            }
            let date = new Date(value);
            if (date.getTime() < new Date().getTime()) {
                callback(new Error("证书到期时间必须大于当前时间！"));
            }
            let issueTime = new Date(this.saveForm.issueTime);
            if (issueTime.getTime() >= date.getTime()) {
                callback(new Error("证书到期时间必须大于发行时间!"));
            }
            callback();
        },
        // 校验证书验证参数格式
        validLicenseCheckModel(rule, value, callback) {
            if (this.saveForm.jsonFormat) {
                if (!value) {
                    callback(new Error('请输入证书验证参数！'));
                }
                if (!isJson(value)) {
                    callback(new Error('请输入json格式的参数！'));
                }
            }
            callback();
        },
        // 校验mac地址
        validMacAddress(rule, value, callback) {
            if (!this.saveForm.jsonFormat) {
                if (!value) {
                    callback(new Error('请输入Mac地址参数！'));
                }
            }
            callback();
        },

        // 保存表单-确定
        saveFormConfirm() {
            const id = this.saveForm.id;
            this.$refs['saveFormRef'].validate((valid) => {
                if (valid && !id) {
                    // 如果id不存在，则新增数据
                    insert(this.saveForm).then((resp => {
                        if (resp && resp.status === 200) {
                            Message.success("新增成功！");
                            this.saveDialogVisible = false;
                            this.initList();
                            this.saveFormReset(true);
                        }
                    }));
                } else if (id) {
                    // 如果id存在，则更新数据
                    update(this.saveForm).then(resp => {
                        if (resp && resp.status === 200) {
                            Message.success("更新成功！")
                            this.saveDialogVisible = false;
                            this.initList();
                            this.saveFormReset(true);
                        }
                    });
                } else {
                    return false;
                }
            });
        },

        // 生成证书下载
        genLicense(row) {
            downloadLicense(row).then(resp => {
                if (resp) {
                    let blob = new Blob([resp], {
                        //下载的文件类型；
                        type: 'application/zip'
                    });
                    let fileName = row.customerName + '-license.zip'; //（修改下载的文件名）
                    if (window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveBlob(blob, fileName);
                        // navigator.msSaveBlob(blob)
                    } else {
                        const link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        link.download = fileName;
                        link.click();
                        window.URL.revokeObjectURL(link.href); //释放内存
                    }
                    Message.success('生成成功！');
                }
            });
        },

        // 复制单元格 公共方法
        handleCopy(obj) {
            this.$copyText(obj).then(
                function() {
                    Message.success('复制成功！');
                },
                function() {
                    Message.error('复制失败，请手动复制！');
                }
            );
        },
    },

};
</script>

<style scoped>

/*统一设置保存对话框中输入框的宽度*/
.saveFormColumnWidth {
    width: 280px;
}

</style>